#include <systemSettingMessage.h>

#include <iostream>
#include <postManager.h>
#include <viewConf.h>

namespace Model {

  int SystemSettingMessage::ReceiveBroadcast(Controller::Broadcast *broadcast)
  {
    using namespace Controller;
    BroadcastType type = broadcast->GetBroadcastType();
    switch(type)
      {
      case BROADCAST_TYPE_CURRENT_ATTACK:{
	currentAttack = static_cast<Model::AttackType>(broadcast->GetDoubleData());
      }break;
      case BROADCAST_TYPE_CHANGE_BACKGROUND:{
	currentBackgroundName = broadcast->GetStringData();
      }break;
      case BROADCAST_TYPE_CHANGE_LANGUAGE:{
	currentLanguage = static_cast<Controller::Language>(broadcast->GetDoubleData());
      }break;
      case BROADCAST_TYPE_WRITE_BACK:{
	WriteBack();
      }break;
      default:break;
      }
    return 0;
  }
  
  int SystemSettingMessage::ReLoadConf()
  {
    //	std::cout<<"SystemSettingMessage::ReLoadConf()\n";
    Controller::PostManager *poster = Controller::PostManager::GetPostManager();
    ModelConf *conf = ModelConf::GetModelConf();
    onshowItems = conf->GetDoubleData("onshowItems");
    currentAttack = static_cast<Model::AttackType>(conf->GetDoubleData("currentAttack"));
    currentBackgroundName = conf->GetStringData("currentBackgroundName");
    currentLanguage = static_cast<Controller::Language>(conf->GetDoubleData("currentLanguage"));
    poster->SetDoubleData(onshowItems);
    poster->SetBroadcastType(Controller::BROADCAST_TYPE_ONSHOW_ATTACKS);
    poster->SendBroadcast();

    using namespace Controller;
    using namespace View;
    poster->SetBroadcastType(Controller::BROADCAST_TYPE_CHANGE_LANGUAGE);
    ViewConf *Vconf = ViewConf::GetViewConf();
    std::string path;
    switch(currentLanguage)
      {
      case LANGUAGE_CHINA:{
        path = VIEW_CONF_PATH + (std::string)"conf/Strings_zh_CN.conf";
      }break;
      case LANGUAGE_USA:{
        path = VIEW_CONF_PATH + (std::string)"conf/Strings_en_US.conf";
      }break;
      default:break;
      }
    Vconf->LoadStrings(path);
    poster->SetDoubleData(currentLanguage);
    poster->SendBroadcast();
    return 0;
  }
    
  bool SystemSettingMessage::WriteBack()
  {
    std::ofstream out;
    char *line = (char*)malloc(256);
    std::string filePath = VIEW_CONF_PATH + (std::string)"msg/ModelDouble.conf";
    out.open(filePath.c_str());
    if(out.is_open()){
      sprintf(line,"onshowItems %d",onshowItems);
      out<<line<<std::endl;
      sprintf(line,"currentAttack %d",currentAttack);
      out<<line<<std::endl;
      sprintf(line,"currentLanguage %d",currentLanguage);
      out<<line<<std::endl;
    }
    out.close();

    filePath = VIEW_CONF_PATH + (std::string)"msg/ModelString.conf";
    out.open(filePath.c_str());
    if(out.is_open()){
      out<<"currentBackgroundName "<<currentBackgroundName<<std::endl;
    }
    out.close();
    return true;
  }
  
}
